package com.dxf.sysadmin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxf.securitys.entity.SecurityUser;
import com.dxf.securitys.entity.User;
import com.dxf.sysadmin.entity.SysUser;
import com.dxf.sysadmin.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 自定义userDetailsService - 认证用户详情
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserServiceImpl;


    /***
     * 2.根据账号获取用户信息和权限
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        SysUser sysUser = sysUserServiceImpl.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getAccount,username));

        if(sysUser.getStatus()==1){
            throw new UsernameNotFoundException("该用户已禁用！");
        }

        // 判断用户是否存在
        if (null == sysUser){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        // 返回UserDetails实现类
        User curUser = new User();
        BeanUtils.copyProperties(sysUser,curUser);

        List<String> authorities = sysUserServiceImpl.selectAuthorityByUserId(sysUser.getId());
        SecurityUser securityUser = new SecurityUser(curUser);
        securityUser.setPermissionValueList(authorities);
        log.info("2.根据账号获取用户信息和权限=={}",securityUser);
        return securityUser;
    }

}
